using System;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using System.Xml.Linq;
using System.Linq;
using MsBuildAxTasks;

namespace MsBuildAxTasks.Tasks
{
    public class AxXpoImport : Task
    {
        private const string autoRunLogfile = "autoRunLog.xml";
        private const string axCliExe = "ax32.exe";

        [Required]
        public string XpoFile { get; set; }

        public string Layer { get; set; }
        public string Layercode { get; set; }
        public string DefaultDir { get; set; }
        public string Config { get; set; }

        [Output]
        public string ImportedWithError { get; set; }

        public override bool Execute()
        {
            try
            {
                AutoRunXml autorun = new AutoRunXml(DefaultDir);
                AxCli cli = new AxCli("4.0", Config);

                Log.LogMessage("Current config profile being used " + cli.Config);

                Log.LogMessage("Creating autorun file {0}", DefaultDir + @"\autorun.xml");
                autorun.ImportWithIds = "true";
                autorun.XpoFile = XpoFile;

                autorun.AddXpoImport();
                autorun.CreateXml(DefaultDir + @"\autorun.xml");

                Log.LogMessage("Running {0}\\{1}", cli.BinPath, axCliExe);
                Log.LogMessage("Importing {0}", XpoFile);

                cli.DefaultDir = DefaultDir;
                cli.Layer = Layer;
                cli.Layerdevcode = Layercode;
                cli.Logfile = autoRunLogfile;
                cli.AutoRun(autorun);
                
                ProcessLog();                
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex);
                return false;
            }

            return true;
        }

        private void ProcessLog()
        {
            XDocument doc = XDocument.Load(DefaultDir + "\\" + autoRunLogfile);
            var query = from c in doc.Descendants("XpoImport").Descendants("Error")
                        select c;

            foreach (XElement result in query)
            {
                Log.LogWarning(result.ToString());
                ImportedWithError = "true";
            }

            if (ImportedWithError == "true")
            {
                Log.LogWarning("Errors found, reading infolog");

                var query2 = from c2 in doc.Descendants("AxaptaAutoRun").Descendants("Infolog")
                             select c2;

                foreach (XElement result in query2)
                {
                    Log.LogWarning(result.ToString());
                }
            }
        }
    }
}
